<template>
  <div class="index" v-loading.fullscreen.lock="fullscreenLoading" element-loading-text="拼命加载中...">
    <input type="file" @change="importFile(this)" id="imFile" style="display: none"
           accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,text/plain"/>
    <a id="downlink"></a>
<!--    <el-button class="button" @click="importContent()">黏贴</el-button>-->

    <!--错误信息提示-->
    <el-dialog title="提示" v-model="errorDialog" size="tiny">
      <span>{{errorMsg}}</span>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="errorDialog=false">确认</el-button>
        </span>
    </el-dialog>
    <!--错误信息提示-->
    <el-dialog title="预览" v-model="preViewDialog" >
      <el-input type="textarea" rows="10" v-model="originalContent" placeholder=""  ></el-input>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="preViewDialog=false">确认</el-button>
        </span>
    </el-dialog>
    <div>
      <h2 style="margin-left:-15%">天气编码转换</h2>
      <div class="left">
        <el-button class="button" type="primary" @click="uploadFile()" style="margin-top: 33%">导入<i class="el-icon-upload el-icon--right"></i></el-button>
        <br/>
        <el-button class="button" type="warning" @click="preViewDialog=true" style="margin-top: 1%">原文<i class="el-icon-search el-icon--right"></i></el-button>
        <br/>
        <el-button class="button" type="success" @click="downloadFile(excelData)" style="margin-top: 1%">导出<i class="el-icon-share el-icon--right"></i></el-button>
      </div>
      <div class="right">
        <el-table :data="excelData" tooltip-effect="dark">
          <el-table-column label="城市" prop="cityName" show-overflow-tooltip></el-table-column>
          <el-table-column label="天气" prop="weather" show-overflow-tooltip></el-table-column>
          <el-table-column label="10000" prop="weatherCode" show-overflow-tooltip></el-table-column>
          <el-table-column label="温度" prop="temperature" show-overflow-tooltip></el-table-column>
          <el-table-column label="30000" prop="otherCode" show-overflow-tooltip v-if="contentType == 3 || contentType == 4"></el-table-column>
          <el-table-column label="48H天气" prop="_48weather" show-overflow-tooltip v-if="contentType == 1 || contentType == 2"></el-table-column>
          <el-table-column label="40000" prop="otherCode" show-overflow-tooltip v-if="contentType == 1 || contentType == 2"></el-table-column>
          <el-table-column label="48H温度" prop="_48temp" show-overflow-tooltip v-if="contentType == 1 || contentType == 2"></el-table-column>
        </el-table>
      </div>
    </div>
    <!--展示导入信息-->

    <el-dialog title="请粘贴要编码的内容" :visible.sync="dialogFormVisible">
      <el-form>
        <el-form-item label="" label-position="left" style="text-align:left">
          <el-select ref="contentTypeNode" v-model="contentType" placeholder="请选择编码类型" @change="selectChange"><el-option v-for="item in contentTypeOption" :key="item.value" :label="item.label" :value="item.value"></el-option></el-select>
        </el-form-item>
        <el-form-item label="" label-position="left">
          <el-input type="textarea" rows="10" v-model="fileContent" placeholder="请粘贴要编码的内容"  @blur="contentBlur" @focus="contentFocus" @change="contenChange"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="contenSure">确 定</el-button>
      </div>
    </el-dialog>
<!--    <input id="fileContentId" ref="fileContentRef" style="display: none" :value="originalContent"></input>-->
<!--    <input id="fileNameId" ref="fileNameRef" style="display: none" :value="fileName"></input>-->
<!--    <input id="dialogFormVisibleId" ref="dialogFormVisibleRef" style="display: none" :value="dialogFormVisible"></input>-->
  </div>
</template>
<style >
  .el-input__inner:focus{
    background-color: #64BEFA;
    border-color: #64BEFA;
  }
  .left {
    margin-left: 1%;
    padding-left: 2%;
    float: left;
    width: 40%;
    height: 500px;
    background-image: url("bk.jpeg");
    background-repeat: no-repeat;
    background-position:center;
    background-size: cover;
  }
  .right {
    margin-left: 44%;
  }
</style>
<script>
  var XLSX = require('xlsx')
  export default {
    name: 'Index',
    data () {
      return {
        fullscreenLoading: false, // 加载中
        imFile: '', // 导入文件el
        outFile: '',  // 导出文件el
        errorDialog: false, // 错误信息弹窗
        preViewDialog: false, // 错误信息弹窗
        errorMsg: '', // 错误信息内容
        excelData: [  // 测试数据
          // {
          //   cityName: '00030',
          //   weather: '00001',
          //   temperature: '22031',
          //   _48weather: '30709',
          //   _48temp: '52026'
          // }
        ],
        fileContent: '', // 用来放要编码的内容
        originalContent: '', // 用来放要上传上来原始的文件内容
        fileName: '', // 用来放文件名
        dialogFormVisible: false, // 用来放预览原文内容窗口的开关
        contentType: null, // 用来放选择哪种编码类型
        contentTypeOption: [ // 编码类型的下拉框选项
          {
            'label': '三明预报',
            'value': 1
          },
          {
            'label': '市天气预报',
            'value': 2
          },
          {
            'label': '旅游景点',
            'value': 3
          },
          {
            'label': '海洋气象',
            'value': 4
          }
        ],
        contentTypeObj: { // 编码类型对象
          1: '三明预报',
          2: '市天气预报',
          3: '旅游景点',
          4: '海洋气象'
        },
        cityData: { // 城市数据
          '荔城': 10001,
          '仙游': 10002,
          '城厢': 10003,
          '秀屿': 10004,
          '涵江': 10005,
          '北岸': 10006,
          '湄洲岛': 10007,
          '南日岛': 10008,
          '钟山': 10010,
          '黄石': 10011,
          '湄洲湾': 10015,
          '平海湾': 10016,
          '兴化湾': 10017,
          '平潭': 10021,
          '崇武': 10022,
          '东山': 10023,
          '涵江工业园区': 10029,
          '广化寺': 10030,
          '菜溪岩': 10032,
          '永兴岩': 10033,
          '九鲤湖': 10034,
          '厦门': 10035,
          '泉州': 10036,
          '福州': 10037,
          '三明': 10038,
          '永安': 10039,
          '尤溪': 10040,
          '沙县': 10041,
          '大田': 10042,
          '明溪': 10043,
          '宁化': 10044,
          '清流': 10045,
          '将乐': 10046,
          '建宁': 10047,
          '泰宁': 10048,
          '涵江国圣酒庄': 10029,
          '枫亭': 10009
        },
        sanming: { // 三明的城市数据
          '三明': '00030',
          '永安': '00031',
          '尤溪': '00032',
          '沙县': '00033',
          '大田': '00034',
          '明溪': '00035',
          '宁化': '00036',
          '清流': '00037',
          '将乐': '00038',
          '建宁': '00039',
          '泰宁': '00040'
        },
        meizhoudao: { // 湄洲岛的不同文件下的编码
          1: 10007,
          2: 10007,
          4: 10019,
          3: 10031
        },
        nanridao: { // 南日岛的不同文件下的编码
          1: 10008,
          2: 10008,
          4: 10018
        },
        weather: { // 天气数据
          '晴': '00',
          '多云': '01',
          '阴': '02',
          '阵雨': '03',
          '雷阵雨': '04',
          '雷阵雨并伴有冰雹': '05',
          '雨夹雪': '06',
          '小雨': '07',
          '中雨': '08',
          '大雨': '09',
          '暴雨': '10',
          '大暴雨': '11',
          '特大暴雨': '12',
          '阵雪': '13',
          '小雪': '14',
          '中雪': '15',
          '大雪': '16',
          '暴雪': '17',
          '雾': '18',
          '冻雨': '19',
          '沙尘暴': '20',
          '小～中雨': '21',
          '中～大雨': '22',
          '大～暴雨': '23',
          '暴雨～大暴雨': '24',
          '大暴雨～特大暴雨': '25',
          '小～中雪': '26',
          '中～大雪': '27',
          '大雪～暴雪': '28',
          '浮尘': '29',
          '扬沙': '30',
          '强沙尘暴': '31'
        }
      }
    },
    mounted () {
      this.imFile = document.getElementById('imFile')
      this.outFile = document.getElementById('downlink')
    },
    methods: {
      parseCityName: function (contentType, cityName) { // 用来转化城市汉字
        if (contentType === 1) {
          cityName = this.sanming[cityName]
        } else if (cityName.trim() === '湄洲岛') {
          cityName = this.meizhoudao[contentType]
        } else if (cityName.trim() === '南日岛') {
          cityName = this.nanridao[contentType]
        } else {
          cityName = this.cityData[cityName]
        }
        return cityName
      },
      parseWeather: function (flag, weather) { // 用来转换天气汉字
        var keys = Object.keys(this.weather)
        keys.sort(function (a, b) {
          return b.length - a.length
        })
        for (var i = 0, len = keys.length; i < len; i++) {
          if (weather.indexOf(keys[i]) !== -1) {
            weather = weather.replace(keys[i], this.weather[keys[i]])
            break
          }
        }
        for (var j = 0, jLen = keys.length; j < jLen; j++) {
          if (weather.indexOf(keys[j]) !== -1) {
            weather = weather.replace(keys[j], this.weather[keys[j]])
            break
          }
        }
        weather = weather.replace(/[\u4e00-\u9fa5|,]+/g, '')
        if (weather.length === 2) {
          weather = weather + weather
        }
        return flag + weather
      },

      parseTemperature: function (flag, temperature) { // 用来转换温度汉字
        // 先预处理下，将零下温度转化下
        if (temperature.trim().indexOf('-') === 0) {
          var temps = temperature.split('到')
          if (temps.length !== 2) {
            temps = temperature.split('〜')
          }
          if (temps.length !== 2) {
            temps = temperature.split('～')
          }
          if (temps.length !== 2) {
            temps = temperature.split('-')
          }
          if (temps.length !== 2) {
            temps = temperature.split('-')
            if (temps.length === 3) {
              temps[0] = '-' + temps[1]
              temps[1] = temps[2]
            } else if (temps.length === 4) {
              temps[0] = '-' + temps[1]
              temps[1] = '-' + temps[3]
            }
          }
          if (temps[0].trim().indexOf('-') === 0) {
            temperature = temperature.replace(temps[0].trim(), (Math.abs(parseInt(temps[0].trim())) + 50).toString())
          }
          if (temps[1].trim().indexOf('-') === 0) {
            temperature = temperature.replace(temps[1].trim(), (Math.abs(parseInt(temps[1].trim())) + 50).toString())
          }
        }

        // 预处理结束，已经将零下温度转化好了
        var temperatureTmp = temperature
        temperature = temperature.replace('℃', '')
        temperature = temperature.replace('〜', '')
        temperature = temperature.replace('～', '')
        temperature = temperature.replace('-', '')
        temperature = temperature.replace(/[\u4e00-\u9fa5|,]+/g, '')
        if (temperature.length < 4) {
          temperatureTmp = temperatureTmp.replace('℃', '')
          var temperatures = temperatureTmp.split('到')
          if (temperatures.length !== 2) {
            temperatures = temperatureTmp.split('〜')
          }
          if (temperatures.length !== 2) {
            temperatures = temperatureTmp.split('～')
          }
          if (temperatures.length !== 2) {
            temperatures = temperatureTmp.split('-')
          }
          temperatures[0] = temperatures[0].replace(/[\u4e00-\u9fa5|,]+/g, '')
          if (temperatures[0].length === 1) {
            temperature = '0' + temperatures[0]
          } else {
            temperature = temperatures[0]
          }
          temperatures[1] = temperatures[1].replace(/[\u4e00-\u9fa5|,]+/g, '')
          if (temperatures[1].length === 1) {
            temperature = temperature + '0' + temperatures[1]
          } else {
            temperature = temperature + temperatures[1]
          }
        }
        return flag + temperature
      },
      parseContent: function (contentType, fileContent) { // 解析要编码的内容
        if (contentType === 1) { // 1三明预报.txt
          var contents = fileContent.split('\r\n')
          if (contents.length === 1) {
            contents = fileContent.split('\n')
          }
          for (var i = 0, len = contents.length; i < len; i++) {
            var content = contents[i]
            var columns = content.trim().split(' ')
            var data = {}
            var jIndex = 0
            for (var j = 0, jLen = columns.length; j < jLen; j++) {
              var column = columns[j]
              if (column.trim() !== '') {
                data[jIndex] = column.trim()
                jIndex++
              }
            }
            var excelData = {}
            if (!data[0]) {
              continue
            }
            excelData['cityName'] = this.parseCityName(contentType, data[0])
            excelData['weather'] = this.parseWeather('0', data[1])
            excelData['temperature'] = this.parseTemperature('2', data[2])
            excelData['_48weather'] = this.parseWeather('3', data[3])
            excelData['_48temp'] = this.parseTemperature('5', data[4])
            excelData['weatherCode'] = '10000'
            if (contentType === 1 || contentType === 2) {
              excelData['otherCode'] = '40000'
            }
            if (contentType === 3 || contentType === 4) {
              excelData['otherCode'] = '30000'
            }
            this.excelData.push(excelData)
          }
        } else if (contentType === 2) { // 2市天气预报.txt
          var _2contents = fileContent.split('--')
          for (var _2i = 0, _2len = _2contents.length; _2i < _2len; _2i++) {
            var _2content = _2contents[_2i]
            if (_2content.trim() === '' || _2content.indexOf('--') !== -1 || _2content === '-') {
              continue
            }
            // console.log(_2content)
            var _2columns = _2content.trim().split(' ')
            var _2data = {}
            var _2jIndex = 0
            for (var _2j = 0, _2jLen = _2columns.length; _2j < _2jLen; _2j++) {
              var _2column = _2columns[_2j]
              _2column = _2column.replace('\r\n', '')
              _2column = _2column.replace('\n', '')
              if (_2column.trim() !== '' && _2column.trim() !== '-') {
                // if (_2jIndex === 5 && Object.keys(this.weather).toString().indexOf(_2column.trim()) === -1) {
                if (_2jIndex === 5 && (_2column.trim().indexOf(',') !== -1 || _2column.trim().indexOf('，') !== -1)) {
                  continue
                }
                _2data[_2jIndex] = _2column.trim()
                _2jIndex++
              }
            }
            var _2excelData = {}
            _2excelData['cityName'] = this.parseCityName(contentType, _2data[1])
            _2excelData['weather'] = this.parseWeather('0', _2data[2])
            _2excelData['temperature'] = this.parseTemperature('2', _2data[4])
            _2excelData['_48weather'] = this.parseWeather('3', _2data[6])
            _2excelData['_48temp'] = this.parseTemperature('5', _2data[7])
            _2excelData['weatherCode'] = '10000'
            if (contentType === 1 || contentType === 2) {
              _2excelData['otherCode'] = '40000'
            }
            if (contentType === 3 || contentType === 4) {
              _2excelData['otherCode'] = '30000'
            }
            this.excelData.push(_2excelData)
          }
        } else if (contentType === 3) { // 3旅游景点.txt //
          fileContent = fileContent.replace(/--/g, '')
          var _3contents = fileContent.split('\r\n')
          if (_3contents.length === 1) {
            _3contents = fileContent.split('\n')
          }
          for (var _3i = 0, _3len = _3contents.length; _3i < _3len; _3i++) {
            var _3content = _3contents[_3i]
            if (_3content.trim() === '') {
              continue
            }
            var _3columns = _3content.trim().split(' ')
            var _3data = {}
            var _3jIndex = 0
            for (var _3j = 0, _3jLen = _3columns.length; _3j < _3jLen; _3j++) {
              var _3column = _3columns[_3j]
              if (_3column.trim() !== '') {
                if (!this.isNum(_3column.trim()) && _3j === 0) {
                  _3jIndex++
                }
                _3data[_3jIndex] = _3column.trim()
                _3jIndex++
              }
            }
            var _3excelData = {}
            _3excelData['cityName'] = this.parseCityName(contentType, _3data[1])
            _3excelData['weather'] = this.parseWeather('0', _3data[2])
            _3excelData['temperature'] = this.parseTemperature('2', _3data[5])
            _3excelData['weatherCode'] = '10000'
            if (contentType === 1 || contentType === 2) {
              _3excelData['otherCode'] = '40000'
            }
            if (contentType === 3 || contentType === 4) {
              _3excelData['otherCode'] = '30000'
            }
            this.excelData.push(_3excelData)
          }
        } else if (contentType === 4) { // 4海洋气象.txt
          fileContent = fileContent.replace(/---/g, '')
          var _4contents = fileContent.split('\r\n')
          if (_4contents.length === 1) {
            _4contents = fileContent.split('\n')
          }
          for (var _4i = 0, _4len = _4contents.length; _4i < _4len; _4i++) {
            var _4content = _4contents[_4i]
            if (_4content.trim() === '') {
              continue
            }
            var _4columns = _4content.trim().split(' ')
            var _4data = {}
            var _4jIndex = 0
            for (var _4j = 0, _4jLen = _4columns.length; _4j < _4jLen; _4j++) {
              var _4column = _4columns[_4j]
              if (_4column.trim() !== '') {
                _4data[_4jIndex] = _4column.trim()
                _4jIndex++
              }
            }
            var _4excelData = {}
            _4excelData['cityName'] = this.parseCityName(contentType, _4data[1])
            _4excelData['weather'] = this.parseWeather('0', _4data[2])
            _4excelData['temperature'] = this.parseTemperature('2', _4data[3])
            _4excelData['weatherCode'] = '10000'
            if (contentType === 1 || contentType === 2) {
              _4excelData['otherCode'] = '40000'
            }
            if (contentType === 3 || contentType === 4) {
              _4excelData['otherCode'] = '30000'
            }
            this.excelData.push(_4excelData)
          }
        }
      },
      contentTypeNodeFocus: function () { // 提示用户要先选编码类型
        if (!this.contentType) {
          this.$message('请选择编码类型')
          this.$nextTick(function () {
            this.$refs.contentTypeNode.$el.querySelector('input').focus()
          })
        }
      },
      contentBlur: function () {
        this.contentTypeNodeFocus()
      },
      contentFocus: function () {
        this.contentTypeNodeFocus()
      },
      contenChange: function () {
        this.contentTypeNodeFocus()
      },
      selectChange: function () {
        this.excelData = []
      },
      contenSure: function () { // 提示用户要粘贴好要编码的内容，然后调用转换方法进行转换
        this.contentTypeNodeFocus()
        if (!this.contentType) {
          return
        }
        if (!this.fileContent) {
          this.$message('请粘贴要编码的内容')
          return
        }
        this.dialogFormVisible = false
        this.excelData = []
        this.parseContent(this.contentType, this.fileContent)
      },
      importContent: function () { // 按钮导入
        this.dialogFormVisible = true
      },
      uploadFile: function () { // 按钮导入
        this.imFile.click()
      },
      downloadFile: function (rs) { // 按钮导出
        var contexts = []
        var contentType = this.contentType
        for (var i = 0; i < rs.length; i++) {
          var context = []
          context.push(rs[i]['cityName'])
          context.push(rs[i]['weather'])
          context.push(rs[i]['weatherCode'])
          context.push(rs[i]['temperature'])
          if (contentType === 3 || contentType === 4) {
            context.push(rs[i]['otherCode'])
          }
          if (rs[i]['_48weather']) {
            context.push(rs[i]['_48weather'])
          }
          if (contentType === 1 || contentType === 2) {
            context.push(rs[i]['otherCode'])
          }
          if (rs[i]['_48temp']) {
            context.push(rs[i]['_48temp'])
          }
          contexts.push(context.join('  '))
        }
        this.textDownload(contexts.join('\r\n'), this.contentTypeObj[this.contentType])
      },
      downloadExcelFile: function (rs) { // 按钮导出
        this.textDownload(JSON.stringify(rs), this.contentTypeObj[this.contentType])
        let data = [{}]
        for (let k in rs[0]) {
          data[0][k] = k
        }
        data = data.concat(rs)
        this.downloadExl(data, this.contentTypeObj[this.contentType])
      },
      dealContent: function (originalContent, fileName) { // 预处理文件内容，将文件内容转成便于解析的内容
        console.log('fileContent:' + originalContent)
        console.log('fileName:' + fileName)
        var begin, end, tmp
        if (fileName.indexOf('三明预报') !== -1) {
          this.contentType = 1
          begin = originalContent.indexOf('48小时预报')
          end = originalContent.lastIndexOf('℃')
          tmp = originalContent.substring('48小时预报'.length + begin + 1, end + 1)
        } else if (fileName.indexOf('市天气预报') !== -1) {
          this.contentType = 2
          begin = originalContent.indexOf('-')
          end = originalContent.lastIndexOf('-')
          tmp = originalContent.substring(begin, end + 1)
        } else if (fileName.indexOf('旅游景点') !== -1) {
          this.contentType = 3
          begin = originalContent.indexOf('-')
          end = originalContent.lastIndexOf('-')
          tmp = originalContent.substring(begin, end + 1)
        } else if (fileName.indexOf('海洋气象') !== -1) {
          this.contentType = 4
          begin = originalContent.indexOf('-')
          end = originalContent.lastIndexOf('-')
          tmp = originalContent.substring(begin, end + 1)
        }
        // console.log('dealContent:' + tmp)
        this.excelData = []
        this.fileContent = tmp
        this.parseContent(this.contentType, this.fileContent)
      },
      importFile: function () { // 导入excel
        this.fullscreenLoading = true
        let obj = this.imFile
        if (!obj.files) {
          this.fullscreenLoading = false
          return
        }
        var f = obj.files[0]
        var reader = new FileReader()
        reader.readAsText(f)
        // var dialogFormVisibleNode = document.getElementById('dialogFormVisibleId')
        // var fileNameNode = document.getElementById('fileNameId')
        // var fileContentNode = document.getElementById('fileContentId')
        var self = this
        reader.onload = function () {
          // 读取完成后，数据保存在对象的result属性中
          // console.log(this.result)
          // console.log(f.name)
          // var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver
          // // var fileContentNode = document.querySelector('fileContentId')
          // var observer = new MutationObserver(function (mutations) {
          //   // console.log('mutations',mutations)
          //   mutations.forEach(function (record) {
          //     if (record.attributeName === 'value') {
          //       console.log('record.target:', record.target.value)
          //       console.log('record.oldValue:', record.oldValue)
          //     }
          //   })
          // })
          // observer.observe(fileContentNode, {
          //   attributes: true,
          //   childList: true,
          //   characterData: true,
          //   attributeOldValue: true,
          //   attributeFilter: ['value'] // 只监听value属性,提高性能
          // })
          self.fullscreenLoading = false
          self.originalContent = this.result
          self.dealContent(this.result, f.name, self)
          // dialogFormVisibleNode.setAttribute('value', false)
          // fileNameNode.setAttribute('value', f.name)
          // fileContentNode.setAttribute('value', this.result)
        }
      },
      importExcelFile: function () { // 导入excel
        this.fullscreenLoading = true
        let obj = this.imFile
        if (!obj.files) {
          this.fullscreenLoading = false
          return
        }
        var f = obj.files[0]
        var reader = new FileReader()
        let $t = this
        reader.onload = function (e) {
          var data = e.target.result
          if ($t.rABS) {
            $t.wb = XLSX.read(btoa(this.fixdata(data)), {  // 手动转化
              type: 'base64'
            })
          } else {
            $t.wb = XLSX.read(data, {
              type: 'binary'
            })
          }
          let json = XLSX.utils.sheet_to_json($t.wb.Sheets[$t.wb.SheetNames[0]])
          console.log(typeof json)
          $t.dealFile($t.analyzeData(json)) // analyzeData: 解析导入数据
        }
        if (this.rABS) {
          reader.readAsArrayBuffer(f)
        } else {
          reader.readAsBinaryString(f)
        }
      },
      downloadExl: function (json, downName, type) {  // 导出到excel
        let keyMap = [] // 获取键
        for (let k in json[0]) {
          keyMap.push(k)
        }
        console.info('keyMap', keyMap, json)
        let tmpdata = [] // 用来保存转换好的json
        json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
          v: v[k],
          position: (j > 25 ? this.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
        }))).reduce((prev, next) => prev.concat(next)).forEach(function (v) {
          tmpdata[v.position] = {
            v: v.v
          }
        })
        let outputPos = Object.keys(tmpdata)  // 设置区域,比如表格从A1到D10
        let tmpWB = {
          SheetNames: ['mySheet'], // 保存的表标题
          Sheets: {
            'mySheet': Object.assign({},
              tmpdata, // 内容
              {
                '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] // 设置填充区域
              })
          }
        }
        let tmpDown = new Blob([this.s2ab(XLSX.write(tmpWB,
          {bookType: (type === undefined ? 'xlsx' : type), bookSST: false, type: 'binary'} // 这里的数据是用来定义导出的格式类型
        ))], {
          type: ''
        })  // 创建二进制对象写入转换好的字节流
        var href = URL.createObjectURL(tmpDown)  // 创建对象超链接
        this.outFile.download = downName + '.csv'  // 下载名称
        this.outFile.href = href  // 绑定a标签
        this.outFile.click()  // 模拟点击实现下载
        setTimeout(function () {  // 延时释放
          URL.revokeObjectURL(tmpDown) // 用URL.revokeObjectURL()来释放这个object URL
        }, 100)
      },
      textDownload: function (content, filename) { // 导出到文本
        var eleLink = document.createElement('a')
        eleLink.download = filename + '.txt'
        eleLink.style.display = 'none' // 字符内容转变成blob地址
        var blob = new Blob([content])
        eleLink.href = URL.createObjectURL(blob) // 触发点击
        document.body.appendChild(eleLink)
        eleLink.click() // 然后移除
        document.body.removeChild(eleLink)
      },
      analyzeData: function (data) {  // 此处可以解析导入数据
        return data
      },
      dealFile: function (data) {   // 处理导入的数据
        console.log(data)
        this.imFile.value = ''
        this.fullscreenLoading = false
        if (data.length <= 0) {
          this.errorDialog = true
          this.errorMsg = '请导入正确信息'
        } else {
          this.excelData = data
        }
      },
      s2ab: function (s) { // 字符串转字符流
        var buf = new ArrayBuffer(s.length)
        var view = new Uint8Array(buf)
        for (var i = 0; i !== s.length; ++i) {
          view[i] = s.charCodeAt(i) & 0xFF
        }
        return buf
      },
      getCharCol: function (n) { // 将指定的自然数转换为26进制表示。映射关系：[0-25] -> [A-Z]。
        let s = ''
        let m = 0
        while (n > 0) {
          m = n % 26 + 1
          s = String.fromCharCode(m + 64) + s
          n = (n - m) / 26
        }
        return s
      },
      fixdata: function (data) {  // 文件流转BinaryString
        var o = ''
        var l = 0
        var w = 10240
        for (; l < data.byteLength / w; ++l) {
          o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)))
        }
        o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)))
        return o
      },
      isNum: function (s) { // 判断是否是数字
        if (s != null) {
          var r, re
          re = /\d*/i  // \d表示数字,*表示匹配多个数字
          r = s.match(re)
          return (r[0] === s)
        }
        return false
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
  .el-table th>.cell {
    text-align: center;
  }
  .button {
    margin-bottom: 20px;
  }
</style>
